// 使用内置的 fetch (Node.js 18+)
const { ethers } = require('ethers');

// 从环境变量读取私钥
require('dotenv').config();

const API_BASE = 'http://localhost:7172/api/bsc';

async function testCreateToken() {
  console.log('Testing BSC Token Creation...');
  
  const tokenData = {
    name: 'Real Test Token',
    symbol: 'REAL',
    description: 'Testing real contract integration with funded wallet',
    website: 'https://realtest.com',
    telegram: 'https://t.me/realtest',
    twitter: 'https://twitter.com/realtest',
    targetAmount: 1, // 降低目标金额到 1 BNB
    creatorPrivateKey: process.env.PRIVATE_KEY // 使用有余额的钱包
  };

  try {
    const response = await fetch(`${API_BASE}/tokens`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(tokenData)
    });

    const result = await response.json();
    console.log('Response:', JSON.stringify(result, null, 2));

    if (result.success) {
      console.log('✅ Token created successfully!');
      console.log('Launch ID:', result.data.launchId);
      console.log('Token Address:', result.data.tokenAddress);
      console.log('Transaction Hash:', result.data.transactionHash);
      return result.data.launchId;
    } else {
      console.log('❌ Token creation failed:', result.error);
      return null;
    }
  } catch (error) {
    console.error('❌ Error:', error.message);
    return null;
  }
}

async function testBuyTokens(launchId) {
  if (!launchId) {
    console.log('❌ No launch ID provided for buying');
    return;
  }

  console.log('\nTesting Token Purchase...');
  
  const buyData = {
    launchId: launchId,
    amount: 0.1, // 购买 0.1 BNB 的代币
    buyerPrivateKey: process.env.PRIVATE_KEY
  };

  try {
    const response = await fetch(`${API_BASE}/tokens/buy`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(buyData)
    });

    const result = await response.json();
    console.log('Buy Response:', JSON.stringify(result, null, 2));

    if (result.success) {
      console.log('✅ Tokens purchased successfully!');
      console.log('Tokens Received:', result.data.purchase.tokenAmount);
      console.log('Total Paid:', result.data.purchase.totalPaid, 'BNB');
      console.log('Transaction Hash:', result.data.purchase.transactionHash);
    } else {
      console.log('❌ Token purchase failed:', result.error);
    }
  } catch (error) {
    console.error('❌ Error:', error.message);
  }
}

async function testGetTokens() {
  console.log('\nTesting Get All Tokens...');
  
  try {
    const response = await fetch(`${API_BASE}/tokens`);
    const result = await response.json();
    console.log('Get Tokens Response:', JSON.stringify(result, null, 2));
  } catch (error) {
    console.error('❌ Error:', error.message);
  }
}

async function main() {
  if (!process.env.PRIVATE_KEY) {
    console.log('❌ PRIVATE_KEY environment variable not set');
    return;
  }

  // 测试创建代币
  const launchId = await testCreateToken();
  
  // 等待一下让交易确认
  if (launchId) {
    console.log('\nWaiting 3 seconds for transaction confirmation...');
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    // 测试购买代币
    await testBuyTokens(launchId);
  }
  
  // 测试获取所有代币
  await testGetTokens();
}

main().catch(console.error);
